//
//  PSPhotoPanelController.m
//  photoSep
//
//  Created by David Michaeli on 03/10/12.
//  Copyright (c) 2012 David Michaeli. All rights reserved.
//

#import "PSPhotoPanelController.h"
#import <AppKit/AppKit.h>
#import "PSFileListController.h"
#import "PSPhotoPanelView.h"
#import "PSFileListNode.h"

@class PSPhotoPanelView;

@implementation PSPhotoPanelController

@synthesize imageView = _imageView;

#define ZOOM_IN_FACTOR  1.414214
#define ZOOM_OUT_FACTOR 0.7071068

-(void) awakeFromNib
{
    [_fileListController addObserver:self forKeyPath:@"currentSelectedNode" options:NSKeyValueObservingOptionNew context:nil];
    
    // customize the IKImageView...
    [_imageView setDoubleClickOpensImageEditPanel: YES];
    //[_imageView setCurrentToolMode: IKToolModeMove];
    //[_imageView zoomImageToFit: self];
    [_imageView setDelegate: self];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    if ([keyPath isEqualToString:@"currentSelectedNode"] )
    {
        PSFileListController* fileList = (PSFileListController*)object;
        PSFileListNode* currentNode = [fileList currentSelectedNode];
        
        if (currentNode == nil)
        {
            [_imageView setImageWithURL:nil];
            [_imageProperties release];
            [_imageUTType release];
            [_window setTitle: @"fotoSep"];
        }
        else
        {
            [self openImageURL:currentNode.url];
        }
    }
}

// ---------------------------------------------------------------------------------------------------------------------
- (void)openImageURL: (NSURL*)url
{
    // use ImageIO to get the CGImage, image properties, and the image-UTType
    //
    CGImageRef          image = NULL;
    CGImageSourceRef    isr = CGImageSourceCreateWithURL( (CFURLRef)url, NULL);
    
    if (isr)
    {
		NSDictionary *options = [NSDictionary dictionaryWithObject: (id)kCFBooleanTrue  forKey: (id) kCGImageSourceShouldCache];
        image = CGImageSourceCreateImageAtIndex(isr, 0, (CFDictionaryRef)options);
        
 /*       if (image)
        {
            _imageProperties = (NSDictionary*)CFBridgingRelease(CGImageSourceCopyPropertiesAtIndex(isr, 0, (CFDictionaryRef)_imageProperties));
            
            _imageUTType = (NSString*)CGImageSourceGetType(isr);
        }
		CFRelease(isr);*/
        
    }
    
    if (image)
    {
        [_imageView setImage: image
             imageProperties: _imageProperties];
		
		CGImageRelease(image);
        
        NSString *title = [NSString stringWithFormat:@"fotoSep - %@", [[url path] lastPathComponent]];
        [_window setTitle: title];
    }
    else
    {
        [_window setTitle: @"fotoSep"];

    }
}

// ---------------------------------------------------------------------------------------------------------------------
- (void)windowDidResize:(NSNotification *)notification
{
    // whenever the window gets resized - do a zoom-to-fit
    
    [CATransaction begin];
    [CATransaction setValue: [NSNumber numberWithFloat: 0]
                     forKey: kCATransactionAnimationDuration];
    [_imageView zoomImageToFit: self];
    [CATransaction commit];
}


// ---------------------------------------------------------------------------------------------------------------------
- (IBAction)switchToolMode: (id)sender
{
    // switch the tool mode...
    
    NSInteger newTool;
    newTool = [sender tag];
    
    switch (newTool)
    {
        case 5:
            [_imageView setCurrentToolMode: IKToolModeMove];
            break;
        case 4:
            [_imageView setCurrentToolMode: IKToolModeRotate];
            break;
        case 6:
            [_imageView setCurrentToolMode: IKToolModeSelect];
            break;
        case 7:
            [_imageView setCurrentToolMode: IKToolModeCrop];
            break;
        case 8:
            [_imageView setCurrentToolMode: IKToolModeAnnotate];
            break;
    }
}

// ---------------------------------------------------------------------------------------------------------------------
- (IBAction)doZoom: (id)sender
{
    // handle zoom tool...
    
    NSInteger zoom;
    CGFloat   zoomFactor;
    
    zoom = [sender tag];
    
    switch (zoom)
    {
        case 2:
            zoomFactor = [_imageView zoomFactor];
            [_imageView setZoomFactor: zoomFactor * ZOOM_OUT_FACTOR];
            break;
        case 1:
            zoomFactor = [_imageView zoomFactor];
            [_imageView setZoomFactor: zoomFactor * ZOOM_IN_FACTOR];
            break;

        case 3:
            [_imageView zoomImageToFit: self];
            break;
    }
}

// ---------------------------------------------------------------------------------------------------------------------
- (void)savePanelDidEnd: (NSSavePanel *)sheet
             returnCode: (NSInteger)returnCode
{
    // save the image
    
    if (returnCode == NSOKButton)
    {
        NSString * newUTType = [_saveOptions imageUTType];
        CGImageRef image;
        
        // get the current image from the image view
        image = [_imageView image];
        
        if (image)
        {
            // use ImageIO to save the image in the user specified format
            NSURL *               url = [sheet URL];
            CGImageDestinationRef dest = CGImageDestinationCreateWithURL((CFURLRef)url, (CFStringRef)newUTType, 1, NULL);
            
            if (dest)
            {
                CGImageDestinationAddImage(dest, image, (CFDictionaryRef)[_saveOptions imageProperties]);
                CGImageDestinationFinalize(dest);
                CFRelease(dest);
            }
        } else
        {
            NSLog(@"*** saveImageToPath - no image");
        }
    }
}

// ---------------------------------------------------------------------------------------------------------------------
- (IBAction)saveImage: (id)sender
{
    // Let the user choose an output file, then start the process of writing samples
	NSSavePanel *savePanel = [NSSavePanel savePanel];
    _saveOptions = [[IKSaveOptions alloc] initWithImageProperties: _imageProperties
                                                      imageUTType: _imageUTType];
    
    [_saveOptions addSaveOptionsAccessoryViewToSavePanel: savePanel];
	[savePanel setCanSelectHiddenExtension:YES];
    [savePanel setNameFieldStringValue:[[_window representedFilename] lastPathComponent]];
	[savePanel beginSheetModalForWindow:_window completionHandler:^(NSInteger result) {
		if (result == NSFileHandlingPanelOKButton)
            [self savePanelDidEnd:savePanel returnCode:result];
	}];
}

@end
